﻿using TianYu.Core.Common;

namespace TianYu.Core.DataBase.Extension
{
    public static class LogContentBuilderExtension
    {
        public static LogContentBuilder Append<TModel>(this LogContentBuilder @this, TModel oldModel, TModel newModel, string propertyName, string fieldName) where TModel : BaseModel, new()
        {
            if (newModel.IsChanged(propertyName))
            {
                var type = oldModel.GetType();
                var property = type.GetProperty(propertyName);
                var propertyType = property.PropertyType;
                var oldValue = property.GetValue(oldModel);
                var newValue = property.GetValue(newModel);
                CheckPropertyValue(@this, fieldName, propertyType, oldValue, newValue);
            }
            return @this;
        }

        private static void CheckPropertyValue(LogContentBuilder logBuilder, string fieldName, Type propertyType, object oldPropertyValue, object newPropertyValue)
        {
            if (propertyType == typeof(string))
            {
                logBuilder.Append(fieldName, (string)oldPropertyValue, (string)newPropertyValue);
            }
            else if (propertyType == typeof(int))
            {
                logBuilder.Append(fieldName, (int)oldPropertyValue, (int)newPropertyValue);
            }
            else if (propertyType == typeof(long))
            {
                logBuilder.Append(fieldName, (long)oldPropertyValue, (long)newPropertyValue);
            }
            else if (propertyType == typeof(decimal))
            {
                logBuilder.Append(fieldName, (decimal)oldPropertyValue, (decimal)newPropertyValue);
            }
            else if (propertyType == typeof(DateTime))
            {
                logBuilder.Append(fieldName, (DateTime)oldPropertyValue, (DateTime)newPropertyValue);
            }
            else if (propertyType == typeof(int?))
            {
                logBuilder.Append(fieldName, (int?)oldPropertyValue, (int?)newPropertyValue);
            }
            else if (propertyType == typeof(long?))
            {
                logBuilder.Append(fieldName, (long?)oldPropertyValue, (long?)newPropertyValue);
            }
            else if (propertyType == typeof(decimal?))
            {
                logBuilder.Append(fieldName, (decimal?)oldPropertyValue, (decimal?)newPropertyValue);
            }
            else if (propertyType == typeof(DateTime?))
            {
                logBuilder.Append(fieldName, (DateTime?)oldPropertyValue, (DateTime?)newPropertyValue);
            }
        }
    }
}
